package com.atguigu.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @title: StockReleaseListener
 * @Author syh
 * @Date: 2022/7/15 0:05
 * @Version 1.0
 */

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;


    @RabbitHandler
    public void handlerStockLockRelease(StockLockedTo to, Message message, Channel channel) throws IOException {

        System.out.println("StockReleaseListener收到解锁库存的消息");

        try {
            wareSkuService.unLockStock(to);
            // 没有异常就是消费成功,通知RabbitMQ库存解锁成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 只要出现异常就将消息重新归队,供其他人继续解锁
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

    }

    /**
     * 监听订单解锁是否成功
     *
     * @param orderTo
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handlerOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("handlerOrderCloseRelease收到订单关闭的消息,准备解锁库存");
        try {
            wareSkuService.unLockStock(orderTo);
            // 没有异常就是消费成功,通知RabbitMQ订单解锁成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 只要出现异常就将消息重新归队,供其他人继续解锁
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
